#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "file_process.h"
#include "common.h"

int cmd_id_write(int id){
	FILE *f = NULL;
	char buff[BUF_SIZE];
	char tmp[20][BUF_SIZE]={0};
	char *p=buff;
	int Lid=0;

	if((f=fopen("conf","r+"))==NULL){
		printf("Open file conf error.\n");
	exit(1);
	}
	//copy file conf to tmp
	while((p=fgets(buff,sizeof(buff),f))!=NULL)
		memcpy(tmp[Lid++],buff,sizeof(buff));
	int i=0;
	rewind(f);
	fclose(f);
	remove("conf");
  
	if((f=fopen("conf","w"))==NULL){
		printf("Open file conf error.\n");
		exit(1);
	}

	i=0;
	char *pch;
	for(;i<Lid;i++){
		if(strstr(tmp[i],"next_id")){
			strcpy(tmp[i],"next_id = ");
			sprintf(tmp[i]+strlen(tmp[i]),"%d\n",id);
		}
		fputs(tmp[i],f);
	}
	fclose(f);
}

int id_read(const char *name){
	FILE *f;
	char buff[BUF_SIZE];
	char *pch;
  
	if((f=fopen("conf","r"))==NULL){
	printf("Open file conf error.\n");
	exit(1);
	}

	while(buff ==  fgets(buff,sizeof(buff),f)){
		pch=(char *)strtok(buff," =\n");
		if(strcmp(name,pch)==0){
			pch = (char *)strtok(NULL," =\n");
			return atoi(pch);
		}else
			continue ;
	}
	fclose(f);
}

int ip_read(const char *name, char *ip){
	FILE *f;
	char buff[BUF_SIZE];
	char *pch;

	if((f=fopen("conf","r"))==NULL){
		printf("Open file conf error.\n");
		exit(1);
	}

	while(buff==fgets(buff,sizeof(buff),f)){
		pch = (char *)strtok(buff," =\n");
		if(strcmp(name,pch) == 0){
			pch = (char *)strtok(NULL," =\n");
			strcpy(ip,pch);
		} else
			continue;
	}
	fclose(f);
	return 0;
}

void cmd_id_update(){
	int id=get_cmd_id();
	cmd_id_write(id+1);
}


int get_server_id(){
	return id_read("server_id");
}

int get_cmd_id(){
	return id_read("next_id");
}

int get_broadcast_ip(char *ip){
	return  ip_read("broadcast_ip",ip);
}

int get_agent_ip(char *ip){
	return ip_read("agent_ip",ip);
}

int write_log(const char* cmd){
	FILE *f;
	if((f=fopen("log","a"))==NULL){
		printf("Open file log error.\n");
		exit(1);
	}

	fprintf(f,"%d : %s\n",get_cmd_id(),cmd);
	fclose(f);

	cmd_id_update();  

	return 0;
}

void print_log(){
	FILE *f;
	char buff[BUF_SIZE];

	if((f=fopen("log","r"))==NULL){
		printf("Open file log error.\n");
		exit(1);
	}

	while(buff==fgets(buff,sizeof(buff),f))
		printf("%s",buff);
	fclose(f);
}
